package service;

import common.Message;
import entity.Chat;
import entity.User;
import tools.ChatViewManage;
import view.ChatView;
import view.FriendList;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

/**
 * 客户端与服务器通信线程
 */
public class ClientThread extends Thread {

    private Socket client;
    private volatile boolean isRunning;
    private ObjectInputStream input;
    private ObjectOutputStream output;

    // 保存用户信息
    private User user;
    private FriendList friendList;

    public ClientThread(Socket client) {
        this.client = client;
        this.isRunning = true;
    }

    public void myStop() {
        this.isRunning = false;
    }

    public void send(Message message) {
        try {
            output = new ObjectOutputStream(client.getOutputStream());
            output.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (isRunning) {
                input = new ObjectInputStream(client.getInputStream());
                Message msg = (Message) input.readObject();
                // 判断消息类型
                switch (msg.getType()) {
                    case GET_FRIENDS:// 获取好友列表
                        ArrayList<User> users = (ArrayList<User>) msg.getContent();
                        friendList.showFriendList(users);
                        break;
                    case GET_CHAT_LIST:// 获取聊天记录
                        ArrayList<Chat> content = (ArrayList<Chat>) msg.getContent();
                        String remark = (String) msg.getRemark();
                        ChatView chatFrame = ChatViewManage.getChatFrame(Integer.parseInt(remark));
                        if (chatFrame != null) {
                            chatFrame.showChats(content);
                        }
                        break;
                    case CHAT_MESSAGE:// 聊天消息
                        new ChatService().receive(msg);
                        break;
                    default:
                        System.out.println("未知类型");
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FriendList getFriendList() {
        return friendList;
    }

    public void setFriendList(FriendList friendList) {
        this.friendList = friendList;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
